package com.sec.etech.sys.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.openbpm.base.api.response.impl.ResultMsg;
import org.openbpm.base.core.id.IdUtil;
import org.openbpm.org.core.model.SysResource;
import org.openbpm.org.rest.controller.SysResourceController;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service("etechResourceService")
public class EtechResourceService {

    @Resource
    JdbcTemplate jdbcTemplate;
    @Resource
    SysResourceController sysResourceController;

    /**
     * 根据资源id查询分配的角色列表
     *
     * @param id
     * @return
     */
    public List<Map<String, Object>> getResourceRoles(String id) {
        String sql = "select b.id_ as roleid,b.name_ as rolename from sys_res_role a " +
                " left join org_role b on a.role_id_ = b.id_ " +
                " where b.id_ >0 and res_id_ = ?  order by CONVERT(b.name_ using gbk) asc";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, id);
        if (CollUtil.isNotEmpty(list)) {
            CollUtil.newArrayList();
        }
        return list;
    }

    /**
     * 保存资源 (包含关联角色)
     * @param jsonObject
     * @return
     * @throws Exception
     */
    public ResultMsg<String> save(JSONObject jsonObject) throws Exception {
        SysResource sysResource = JSONUtil.toBean(jsonObject, SysResource.class);
        ResultMsg<String> resultMsg = sysResourceController.save(sysResource);
        if (resultMsg != null && resultMsg.getIsOk() && resultMsg.getData() != null) {
            String id = resultMsg.getData();
            List<String> newroleids = new ArrayList<>();
            if (jsonObject.get("roles") != null) {
                List<Map> list = JSONUtil.toList(jsonObject.getJSONArray("roles"), Map.class);
                for (Map map : list) {
                    newroleids.add(MapUtil.getStr(map, "roleid"));
                }
                List<String> oldroleids = new ArrayList<>();
                List<Map<String, Object>> roles = getResourceRoles(id);
                for (Map<String, Object> role : roles) {
                    oldroleids.add(MapUtil.getStr(role, "roleid"));
                }
                for (String newroleid : newroleids) {
                    if (!oldroleids.contains(newroleid)) {
                        String sql = "INSERT INTO sys_res_role(`ID_`, `SYSTEM_ID_`, `res_id_`, `role_id_`) VALUES " +
                                "(?, ?, ?, ?);";
                        jdbcTemplate.update(sql, IdUtil.getSuid(), sysResource.getSystemId(), id, newroleid);
                    }
                }
            }
            String sql = "delete a from sys_res_role a " +
                    " left join org_role b on a.role_id_ = b.id_" +
                    " where b.id_ >0 and res_id_ = '{}' ";
            if (CollUtil.isNotEmpty(newroleids)) {
                sql += " and b.id_ not in ({})";
            } else {
                sql += " {}";
            }
            jdbcTemplate.execute(StrUtil.format(sql, id, StrUtil.join(",", newroleids)));
        }
        return resultMsg;
    }

    /**
     * 根据账号获取用户信息
     * @param account
     * @return
     * @throws Exception
     */
    public Map<String,Object> getUserByAccount(String account) throws Exception {
        List<Map<String,Object>> userList = jdbcTemplate.queryForList("select * from org_user where account_=?", account);
        return userList!=null && userList.size()>0? userList.get(0): null;
    }
}
